import java.util.Arrays;

/**
* @description: 948. 令牌放置
* @author hewei
* @date 2022/9/22 16:29
* @version 1.0
*/

public class BagOfTokensScore {

    public int bagOfTokensScore(int[] tokens, int power) {
        Arrays.sort(tokens);
        int l = 0;
        int r = tokens.length - 1;
        int ans = 0;
        while (l <= r) {
            if (power >= tokens[l]) {
                power -= tokens[l++];
                ans += 1;
            } else {
                if (l == r) return ans;
                if (ans <= 0) return 0;
                ans -= 1;
                power += tokens[r--];
            }
        }
        return ans;
    }
}
